package com.knowledge.plus.单例多例.demo;

import com.knowledge.plus.单例多例.demo.service.ExampleService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author PF.Tian
 * @since 2021/09/13
 */
@RestController
@RequestMapping("ExampleController")
public class ExampleController {
    /**
     * 单例
     */
    @Autowired
    private ExampleService exampleService;

    @GetMapping("instance1")
    public void SingleInstance() {
        // 每个请求过来的时候，exampleService实例均为同一个实例
        exampleService.test();
    }

    /**
     * 多例，注入方式一
     */
    @Autowired
    private BeanFactory beanFactory;

    @RequestMapping("instance2")
    public void multipleInstance() {
        // 多例模式，必须从bean工厂获取bean才能够实现。
        ExampleService exampleService = beanFactory.getBean(ExampleService.class);
        exampleService.test();
    }

    /**
     * 多例，注入方式二
     */
    @Autowired
    private ObjectFactory<ExampleService> testService;

    @GetMapping("instance3")
    public String multipleInstance2() {
        System.out.println(testService.getObject());
        return testService.getObject().toString();
    }

}
